{{#
Pass strings that correspond to XCCDF value names as arguments to this macro::

    bash_instantiate_variables("varname1", "varname2")

Then, assume that variables of that names are defined and contain the correct value, e.g.::

        echo "Setting=$varname1" >> config_file

#}}
{{%- macro bash_instantiate_variables() -%}}
{{%- for name in varargs -%}}
{{{ name }}}='(bash-populate {{{ name }}})'
{{% endfor -%}}
{{%- endmacro -%}}


{{#
    Make sure that we have a line like this in pamFile (additional options are left as-is):
    type control module option=valueRegexArg

:param pamFile:         PAM config file
:param type:            PAM module interface
:param control:         PAM control flags
:param module:          PAM module name
:param option:          PAM module option
:param valueRegexArg:   PAM module option argument regex pattern
:param defaultValueArg: PAM module option argument default value

#}}
{{%- macro bash_ensure_pam_module_options(pamFile, type, control, module, option, valueRegexArg, defaultValueArg) -%}}
if [ -e "{{{ pamFile }}}" ] ; then
    valueRegex="{{{ valueRegexArg }}}" defaultValue="{{{ defaultValueArg }}}"
    # non-empty values need to be preceded by an equals sign
    [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
    # add an equals sign to non-empty values
    [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

    # fix 'type' if it's wrong
    if grep -q -P "^\\s*(?"'!'"{{{ type }}}\\s)[[:alnum:]]+\\s+[[:alnum:]]+\\s+{{{ module }}}" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*)[[:alnum:]]+(\\s+[[:alnum:]]+\\s+{{{ module }}})/\\1{{{ type }}}\\2/" "{{{ pamFile }}}"
    fi

    # fix 'control' if it's wrong
    if grep -q -P "^\\s*{{{ type }}}\\s+(?"'!'"{{{ control }}})[[:alnum:]]+\\s+{{{ module }}}" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+)[[:alnum:]]+(\\s+{{{ module }}})/\\1{{{ control }}}\\2/" "{{{ pamFile }}}"
    fi

    # fix the value for 'option' if one exists but does not match 'valueRegex'
    if grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}(?"'!'"${valueRegex}(\\s|\$))" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s){{{ option }}}=[^[:space:]]*/\\1{{{ option }}}${defaultValue}/" "{{{ pamFile }}}"

    # add 'option=default' if option is not set
    elif grep -q -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" &&
            grep    -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" | grep -q -E -v "\\s{{{ option }}}(=|\\s|\$)" ; then

        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}[^\\n]*)/\\1 {{{ option }}}${defaultValue}/" "{{{ pamFile }}}"
    # add a new entry if none exists
    elif ! grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}${valueRegex}(\\s|\$)" < "{{{ pamFile }}}" ; then
        echo "{{{ type }}} {{{ control }}} {{{ module }}} {{{ option }}}${defaultValue}" >> "{{{ pamFile }}}"
    fi
else
    echo "{{{ pamFile }}} doesn't exist" >&2
fi
{{%- endmacro -%}}


{{#
    Make sure that we have a line with given type, control and module has the given option in pamFile (additional options are left as-is):
    `type control module option=valueRegexArg`

:param pamFile:        PAM config file
:param type:           PAM module interface
:param control:        PAM control flags
:param module:         PAM module name
:param option:         PAM module option
:param valueRegexArg:   PAM module option argument regex pattern
:param defaultValueArg: PAM module option argument default value

#}}
{{%- macro bash_provide_pam_module_options(pamFile, type, control, module, option, valueRegexArg, defaultValueArg) -%}}
if [ -e "{{{ pamFile }}}" ] ; then
    valueRegex="{{{ valueRegexArg }}}" defaultValue="{{{ defaultValueArg }}}"
    # non-empty values need to be preceded by an equals sign
    [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
    # add an equals sign to non-empty values
    [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

    # fix the value for 'option' if one exists but does not match 'valueRegex'
    if grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}(?"'!'"${valueRegex}(\\s|\$))" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s){{{ option }}}=[^[:space:]]*/\\1{{{ option }}}${defaultValue}/" "{{{ pamFile }}}"

    # add 'option=default' if option is not set
    elif grep -q -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" &&
            grep    -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" | grep -q -E -v "\\s{{{ option }}}(=|\\s|\$)" ; then

        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}[^\\n]*)/\\1 {{{ option }}}${defaultValue}/" "{{{ pamFile }}}"
    # add a new entry if none exists
    elif ! grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}${valueRegex}(\\s|\$)" < "{{{ pamFile }}}" ; then
        echo "{{{ type }}} {{{ control }}} {{{ module }}} {{{ option }}}${defaultValue}" >> "{{{ pamFile }}}"
    fi
else
    echo "{{{ pamFile }}} doesn't exist" >&2
fi
{{%- endmacro -%}}


{{%- set in_chrooted_environment = 'test "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)"' -%}}
{{#
    Set a parameter

:param path: Path to file
:type path: str
:param parameter: Parameter to set
:type parameter: str
:param value: Value to set
:type value: str
:param no_quotes: Boolean, if true the value is not quoted. Default is false.
:type no_quotes: str

#}}
{{%- macro bash_shell_file_set(path, parameter, value, no_quotes=false) -%}}
{{% if no_quotes -%}}
  {{% if "$" in value %}}
    {{% set value = '%s' % value.replace("$", "\\$") %}}
  {{% endif %}}
{{%- else -%}}
  {{% if "$" in value %}}
    {{% set value = '\\"%s\\"' % value.replace("$", "\\$") %}}
  {{% else %}}
    {{% set value = "'%s'" % value %}}
  {{% endif %}}
{{%- endif -%}}
{{{ set_config_file(
        path=path,
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="^#\s*" ~ parameter,
        insensitive=false,
        separator="=",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
    Macro to perform remediation for 'audit_rules_privileged_commands' rule


:param tool:		    tool used to load audit rules either 'auditctl' or 'augenrules'
:param min_auid:		minimum original ID the user logged in with

    Example macro invocation(s)::

         perform_audit_rules_privileged_commands_remediation("auditctl", "500")
         perform_audit_rules_privileged_commands_remediation("augenrules", "1000")

#}}
{{%- macro bash_perform_audit_rules_privileged_commands_remediation(tool, min_auid) -%}}
files_to_inspect=()
{{% if tool == "auditctl" %}}
# If the audit tool is 'auditctl', then:
# * add '/etc/audit/audit.rules'to the list of files to be inspected,
# * specify '/etc/audit/audit.rules' as the output audit file, where
#   missing rules should be inserted
files_to_inspect=("/etc/audit/audit.rules")
output_audit_file="/etc/audit/audit.rules"
{{%- elif tool == "augenrules" -%}}
# If the audit tool is 'augenrules', then:
# * add '/etc/audit/rules.d/*.rules' to the list of files to be inspected
#   (split by newline),
# * specify /etc/audit/rules.d/privileged.rules' as the output file, where
#   missing rules should be inserted
readarray -t files_to_inspect < <(find /etc/audit/rules.d -maxdepth 1 -type f -name '*.rules' -print)
output_audit_file="/etc/audit/rules.d/privileged.rules"
{{%- else -%}}
{{{ raise("Unknown tool used: " + tool) }}}
{{%- endif %}}

# Obtain the list of SUID/SGID binaries on the particular system (split by newline)
# into privileged_binaries array
privileged_binaries=()
readarray -t privileged_binaries < <(find / -not \( -fstype afs -o -fstype ceph -o -fstype cifs -o -fstype smb3 -o -fstype smbfs -o -fstype sshfs -o -fstype ncpfs -o -fstype ncp -o -fstype nfs -o -fstype nfs4 -o -fstype gfs -o -fstype gfs2 -o -fstype glusterfs -o -fstype gpfs -o -fstype pvfs2 -o -fstype ocfs2 -o -fstype lustre -o -fstype davfs -o -fstype fuse.sshfs \) -type f \( -perm -4000 -o -perm -2000 \) 2> /dev/null)

# Keep list of SUID/SGID binaries that have been already handled within some previous iteration
sbinaries_to_skip=()

# For each found sbinary in privileged_binaries list
for sbinary in "${privileged_binaries[@]}"
do

    # Check if this sbinary wasn't already handled in some of the previous sbinary iterations
    # Return match only if whole sbinary definition matched (not in the case just prefix matched!!!)
    if [[ $(sed -ne "\|${sbinary}|p" <<< "${sbinaries_to_skip[*]}") ]]
    then
        # If so, don't process it second time & go to process next sbinary
        continue
    fi

    # Reset the counter of inspected files when starting to check
    # presence of existing audit rule for new sbinary
    count_of_inspected_files=0

    # Define expected rule form for this binary
    expected_rule="-a always,exit -F path=${sbinary} -F auid>={{{ min_auid }}} -F auid!=unset -F key=privileged"

    # If list of audit rules files to be inspected is empty, just add new rule and move on to next binary
    if [[ ${#files_to_inspect[@]} -eq 0 ]]; then
        echo "$expected_rule" >> "$output_audit_file"
        continue
    fi

    # Replace possible slash '/' character in sbinary definition so we could use it in sed expressions below
    sbinary_esc=${sbinary//$'/'/$'\/'}

    # For each audit rules file from the list of files to be inspected
    for afile in "${files_to_inspect[@]}"
    do
        # Search current audit rules file's content for match. Match criteria:
        # * existing rule is for the same SUID/SGID binary we are currently processing (but
        #   can contain multiple -F path= elements covering multiple SUID/SGID binaries)
        # * existing rule contains all arguments from expected rule form (though can contain
        #   them in arbitrary order)

        base_search=$(sed -e '/-a always,exit/!d' -e '/-F path='"${sbinary_esc}"'[^[:graph:]]/!d'		\
                -e '/-F path=[^[:space:]]\+/!d'						\
                -e '/-F auid>='"{{{ min_auid }}}"'/!d' -e '/-F auid!=\(4294967295\|unset\)/!d'	\
                -e '/-k \|-F key=/!d' "$afile")

        # Increase the count of inspected files for this sbinary
        count_of_inspected_files=$((count_of_inspected_files + 1))

        # Search current audit rules file's content for presence of rule pattern for this sbinary
        if [[ $base_search ]]
        then

            # Current audit rules file already contains rule for this binary =>
            # Store the exact form of found rule for this binary for further processing
            concrete_rule=$base_search

            # Select all other SUID/SGID binaries possibly also present in the found rule

            readarray -t handled_sbinaries < <(grep -o -e "-F path=[^[:space:]]\+" <<< "$concrete_rule")
            handled_sbinaries=("${handled_sbinaries[@]//-F path=/}")

            # Merge the list of such SUID/SGID binaries found in this iteration with global list ignoring duplicates
            readarray -t sbinaries_to_skip < <(for i in "${sbinaries_to_skip[@]}" "${handled_sbinaries[@]}"; do echo "$i"; done | sort -du)

            # if there is a -F perm flag, remove it
            if grep -q '.*-F\s\+perm=[rwxa]\+.*' <<< "$concrete_rule"; then

                # Separate concrete_rule into three sections using hash '#'
                # sign as a delimiter around rule's permission section borders
                # note that the trailing space after perm flag is captured because there would be
                # two consecutive spaces after joining remaining parts of the rule together
                concrete_rule="$(echo "$concrete_rule" | sed -n "s/\(.*\)\+\(-F perm=[rwax]\+\ \?\)\+/\1#\2#/p")"

                # Split concrete_rule into head and tail sections using hash '#' delimiter
                # The second column contains the permission section, which we don't need to extract
                rule_head=$(cut -d '#' -f 1 <<< "$concrete_rule")
                rule_tail=$(cut -d '#' -f 3 <<< "$concrete_rule")

                # Remove permissions section from existing rule in the file
                sed -i "s#${rule_head}\(.*\)${rule_tail}#${rule_head}${rule_tail}#" "$afile"
            fi
        # If the required audit rule for particular sbinary wasn't found yet, insert it under following conditions:
        #
        # * in the "auditctl" mode of operation insert particular rule each time
        #   (because in this mode there's only one file -- /etc/audit/audit.rules to be inspected for presence of this rule),
        #
        # * in the "augenrules" mode of operation insert particular rule only once and only in case we have already
        #   searched all of the files from /etc/audit/rules.d/*.rules location (since that audit rule can be defined
        #   in any of those files and if not, we want it to be inserted only once into /etc/audit/rules.d/privileged.rules file)
        #
	{{% if tool in ("augenrules", "auditctl") -%}}
	{{% if tool == "augenrules" -%}}
        elif [[ $count_of_inspected_files -eq "${#files_to_inspect[@]}" ]]
        then
	{{%- endif %}}
	{{% if tool == "auditctl" -%}}
        else
	{{%- endif %}}
            # Check if this sbinary wasn't already handled in some of the previous afile iterations
            # Return match only if whole sbinary definition matched (not in the case just prefix matched!!!)
            if [[ ! $(sed -ne "\|${sbinary}|p" <<< "${sbinaries_to_skip[*]}") ]]
            then
                # Current audit rules file's content doesn't contain expected rule for this
                # SUID/SGID binary yet => append it
                echo "$expected_rule" >> "$output_audit_file"
            fi
            continue
	{{%- endif %}}
        fi
    done
done
{{%- endmacro -%}}


{{#
    Set set a parameter in /etc/sshd_config

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_sshd_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/ssh/sshd_config",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="^Match",
        insensitive=true,
        separator=" ",
        separator_regex="\s\+",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
        Set set a parameter in /etc/sshd_config or /etc/ssh/sshd_config.d/

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str
:parameter config_is_distributed: If true, will ok look in /etc/ssh/sshd_config.d
:type config_is_distributed: str
:parameter config_basename: Filename of configuration file when using distributed configuration
:type config_basename: str

#}}
{{% macro bash_sshd_remediation(parameter, value, config_is_distributed, config_basename="00-complianceascode-hardening.conf") -%}}
{{%- set sshd_config_path = "/etc/ssh/sshd_config" %}}
{{%- set sshd_config_dir = "/etc/ssh/sshd_config.d" -%}}

{{%- if config_is_distributed == "true" %}}
{{%- set prefix_regex = "^\s*" -%}}
{{%- set separator_regex = "\s\+" -%}}
{{%- set hardening_config_basename = config_basename %}}
{{%- set line_regex = prefix_regex ~ parameter ~ separator_regex %}}
mkdir -p {{{ sshd_config_dir }}}
touch {{{ sshd_config_dir }}}/{{{ hardening_config_basename }}}
{{{ lineinfile_absent(sshd_config_path, line_regex, insensitive=true) }}}
{{{ lineinfile_absent_in_directory(sshd_config_dir, line_regex, insensitive=true, filename_glob="*.conf") }}}
{{{ set_config_file(
        path=sshd_config_dir ~ "/" ~ hardening_config_basename,
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="^Match",
        insensitive=true,
        separator=" ",
        separator_regex=separator_regex,
        prefix_regex=prefix_regex)
    }}}
{{%- else %}}
{{% if product in ["ol8", "ol9"] %}}
# Find the include keyword, extract from the line the glob expression representing included files.
# And if it is a relative path prepend '/etc/ssh/'
included_files=$(grep -oP "^\s*(?i)include.*" /etc/ssh/sshd_config | sed -e 's/Include\s*//i' | sed -e 's|^[^/]|/etc/ssh/&|')
for included_file in ${included_files} ; do
    {{{ lineinfile_absent("$included_file", "^\s*" ~ parameter, insensitive=true) | indent(4) }}}
done
{{% endif %}}
{{{ bash_sshd_config_set(parameter=parameter, value=value) }}}
{{%- endif %}}
{{%- endmacro %}}

{{#
    Macro that copies the audit rules into a file.
    The purpose is to create exactly the same content in the file specified by filename argument
    as in https://github.com/linux-audit/audit-userspace/blob/master/rules/30-ospp-v42.rules

:param filename:    Name of the file to print the information to; written do directory specified by the filename
:type filename: str

#}}
{{%- macro bash_create_audit_remediation_unsuccessful_file_modification_detailed(filename) -%}}
mkdir -p "$(dirname '{{{ filename }}}')"
cat <<EOF > "{{{ filename }}}"
{{{ audit_remediation_unsuccessful_file_modification_detailed_audit_file_content() }}}
EOF
{{%- endmacro -%}}

{{#
   Set parameter in /etc/audit/auditd.conf

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_auditd_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/audit/auditd.conf",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator=" = ",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
   Set parameter in /etc/systemd/coredump.conf

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_coredump_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/systemd/coredump.conf",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator="=",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
   Set parameter in /etc/selinux/config

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_selinux_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/selinux/config",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator="=",
        separator_regex="=",
        prefix_regex="^")
    }}}
{{%- endmacro -%}}


{{#
    Macro to fix audit file system object watch rule for given path:
    * if rule exists, also verifies the -w bits match the requirements
    * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
      audit rules file, depending on the tool which was used to load audit rules


:param audit tool                      tool used to load audit rules, either 'auditctl', or 'augenrules'
:param path:                          	value of -w audit rule's argument
:param required_access_bits:       	    value of -p audit rule's argument
:param key:                        	value of -k audit rule's argument

    Example macro invocation::

          {{{ bash_fix_audit_watch_rule("auditctl", "/etc/localtime", "wa", "audit_time_rules") }}}

#}}
{{%- macro bash_fix_audit_watch_rule(tool, path, required_access_bits, key) -%}}
# Create a list of audit *.rules files that should be inspected for presence and correctness
# of a particular audit rule. The scheme is as follows:
#
# -----------------------------------------------------------------------------------------
# Tool used to load audit rules	| Rule already defined	|  Audit rules file to inspect	  |
# -----------------------------------------------------------------------------------------
#	auditctl		|     Doesn't matter	|  /etc/audit/audit.rules	  |
# -----------------------------------------------------------------------------------------
# 	augenrules		|          Yes		|  /etc/audit/rules.d/*.rules	  |
# 	augenrules		|          No		|  /etc/audit/rules.d/$key.rules  |
# -----------------------------------------------------------------------------------------
files_to_inspect=()

{{% if tool == "auditctl" %}}
# If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
# into the list of files to be inspected
files_to_inspect+=('/etc/audit/audit.rules')
{{%- elif tool == "augenrules" -%}}
# If the audit is 'augenrules', then check if rule is already defined
# If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
# If rule isn't defined, add '/etc/audit/rules.d/{{{ key }}}.rules' to list of files for inspection.
readarray -t matches < <(grep -HP "[\s]*-w[\s]+{{{ path }}}" /etc/audit/rules.d/*.rules)

# For each of the matched entries
for match in "${matches[@]}"
do
    # Extract filepath from the match
    rulesd_audit_file=$(echo $match | cut -f1 -d ':')
    # Append that path into list of files for inspection
    files_to_inspect+=("$rulesd_audit_file")
done
# Case when particular audit rule isn't defined yet
if [ "${#files_to_inspect[@]}" -eq "0" ]
then
    # Append '/etc/audit/rules.d/{{{ key }}}.rules' into list of files for inspection
    key_rule_file="/etc/audit/rules.d/{{{ key }}}.rules"
    # If the {{{ key }}}.rules file doesn't exist yet, create it with correct permissions
    if [ ! -e "$key_rule_file" ]
    then
        touch "$key_rule_file"
        chmod 0640 "$key_rule_file"
    fi
    files_to_inspect+=("$key_rule_file")
fi
{{%- else -%}}
{{{ raise("Unknown tool used: " + tool) }}}
{{%- endif %}}

# Finally perform the inspection and possible subsequent audit rule
# correction for each of the files previously identified for inspection
for audit_rules_file in "${files_to_inspect[@]}"
do
    # Check if audit watch file system object rule for given path already present
    if grep -q -P -- "^[\s]*-w[\s]+{{{ path }}}" "$audit_rules_file"
    then
        # Rule is found => verify yet if existing rule definition contains
        # all of the required access type bits

        # Define BRE whitespace class shortcut
        sp="[[:space:]]"
        # Extract current permission access types (e.g. -p [r|w|x|a] values) from audit rule
        current_access_bits=$(sed -ne "s#$sp*-w$sp\+{{{ path }}} $sp\+-p$sp\+\([rxwa]\{1,4\}\).*#\1#p" "$audit_rules_file")
        # Split required access bits string into characters array
        # (to check bit's presence for one bit at a time)
        for access_bit in $(echo "{{{ required_access_bits }}}" | grep -o .)
        do
            # For each from the required access bits (e.g. 'w', 'a') check
            # if they are already present in current access bits for rule.
            # If not, append that bit at the end
            if ! grep -q "$access_bit" <<< "$current_access_bits"
            then
                # Concatenate the existing mask with the missing bit
                current_access_bits="$current_access_bits$access_bit"
            fi
        done
        # Propagate the updated rule's access bits (original + the required
        # ones) back into the /etc/audit/audit.rules file for that rule
        sed -i "s#\($sp*-w$sp\+{{{ path }}}$sp\+-p$sp\+\)\([rxwa]\{1,4\}\)\(.*\)#\1$current_access_bits\3#" "$audit_rules_file"
    else
        # Rule isn't present yet. Append it at the end of $audit_rules_file file
        # with proper key

        echo "-w {{{ path }}} -p {{{ required_access_bits }}} -k {{{ key }}}" >> "$audit_rules_file"
    fi
done
{{%- endmacro -%}}


{{#
    Install a package

    Uses the right command based on pkg_manager property defined in product.yml.

:param package: name of the package
:type package: str

#}}
{{%- macro bash_package_install(package) -%}}
{{%- if pkg_manager is defined -%}}
{{%- if pkg_manager == "yum" or pkg_manager == "dnf" -%}}
if ! rpm -q --quiet "{{{ package }}}" ; then
    {{{ pkg_manager }}} install -y "{{{ package }}}"
fi
{{%- elif pkg_manager == "apt_get" -%}}
DEBIAN_FRONTEND=noninteractive apt-get install -y "{{{ package }}}"
{{%- elif pkg_manager == "zypper" -%}}
zypper install -y "{{{ package }}}"
{{%- else -%}}
{{{ die("Can't generate a remediation for " + pkg_manager) }}}
{{%- endif -%}}
{{%- else -%}}
{{{ die("Can't generate a remediation for product " + product + ", because there is no pkg_manager set in product.yml") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Remove a package

    Uses the right command based on pkg_manager property defined in product.yml.
    When used in a test scenario, the macro will remove even protected packages.

:param package: name of the package
:type package: str

#}}
{{%- macro bash_package_remove(package) -%}}
{{%- if pkg_manager is defined -%}}
{{%- if pkg_manager == "yum" or pkg_manager == "dnf" -%}}
if rpm -q --quiet "{{{ package }}}" ; then
{{% if SSG_TEST_SUITE_ENV %}}
    rpm -e --nodeps "{{{ package }}}"
{{% else %}}
    {{{ pkg_manager }}} remove -y "{{{ package }}}"
{{% endif %}}
fi
{{%- elif pkg_manager == "apt_get" -%}}
DEBIAN_FRONTEND=noninteractive apt-get remove -y "{{{ package }}}"
{{%- elif pkg_manager == "zypper" -%}}
zypper remove -y "{{{ package }}}"
{{%- else -%}}
{{{ die("Can't generate a remediation for " + pkg_manager) }}}
{{%- endif -%}}
{{%- else -%}}
{{{ die("Can't generate a remediation for product " + product + ", because there is no pkg_manager set in product.yml") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Macro to perform remediation for the 'adjtimex', 'settimeofday', and 'stime' audit
    system calls on RHEL, Fedora or OL systems.
    Remediation performed for both possible tools: 'auditctl' and 'augenrules'.

     Note: 'stime' system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
     therefore excluded from the list of time group system calls to be audited on this arch

    Example macro invocation::

      {{{ bash_perform_audit_adjtimex_settimeofday_stime_remediation() }}}

#}}
{{%- macro bash_perform_audit_adjtimex_settimeofday_stime_remediation() -%}}
# Retrieve hardware architecture of the underlying system
[ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

for ARCH in "${RULE_ARCHS[@]}"
do
    # Create expected audit group and audit rule form for particular system call & architecture
    if [ ${ARCH} = "b32" ]
    then
        ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
        # stime system call is known at 32-bit arch (see e.g "$ ausyscall i386 stime" 's output)
        # so append it to the list of time group system calls to be audited
        SYSCALL="adjtimex settimeofday stime"
        SYSCALL_GROUPING="adjtimex settimeofday stime"
    elif [ ${ARCH} = "b64" ]
    then
        ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
        # stime system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
        # therefore don't add it to the list of time group system calls to be audited
        SYSCALL="adjtimex settimeofday"
        SYSCALL_GROUPING="adjtimex settimeofday"
    fi
    OTHER_FILTERS=""
    AUID_FILTERS=""
    KEY="audit_time_rules"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    {{{ bash_fix_audit_syscall_rule("augenrules", "$ACTION_ARCH_FILTERS", "$OTHER_FILTERS", "$AUID_FILTERS", "$SYSCALL", "$SYSCALL_GROUPING", "$KEY") | indent(4) }}}
    {{{ bash_fix_audit_syscall_rule("auditctl", "$ACTION_ARCH_FILTERS", "$OTHER_FILTERS", "$AUID_FILTERS", "$SYSCALL", "$SYSCALL_GROUPING", "$KEY") | indent(4) }}}
done
{{%- endmacro -%}}

{{#
    Disable prelinking in sysconfig
#}}
{{%- macro bash_disable_prelink() -%}}
# prelink not installed
if test -e /etc/sysconfig/prelink -o -e /usr/sbin/prelink; then
    if grep -q ^PRELINKING /etc/sysconfig/prelink
    then
        sed -i 's/^PRELINKING[:blank:]*=[:blank:]*[:alpha:]*/PRELINKING=no/' /etc/sysconfig/prelink
    else
        printf '\n' >> /etc/sysconfig/prelink
        printf '%s\n' '# Set PRELINKING=no per security requirements' 'PRELINKING=no' >> /etc/sysconfig/prelink
    fi

    # Undo previous prelink changes to binaries if prelink is available.
    if test -x /usr/sbin/prelink; then
        /usr/sbin/prelink -ua
    fi
fi
{{%- endmacro -%}}


{{#
    Macro to configure DConf settings for RHEL and Fedora systems.

    If files contain ibus or distro, ignore them.
#}}
{{%- macro bash_dconf_settings(path, key, value, db, setting_file) -%}}
# Check for setting in any of the DConf db directories
# If files contain ibus or distro, ignore them.
# The assignment assumes that individual filenames don't contain :
readarray -t SETTINGSFILES < <(grep -r "\\[{{{ path }}}\\]" "/etc/dconf/db/" \
                                | grep -v 'distro\|ibus\|{{{ db }}}' | cut -d":" -f1)
DCONFFILE="/etc/dconf/db/{{{ db }}}/{{{ setting_file }}}"
DBDIR="/etc/dconf/db/{{{ db }}}"

mkdir -p "${DBDIR}"

# Comment out the configurations in databases different from the target one
if [ "${#SETTINGSFILES[@]}" -ne 0 ]
then
    if grep -q "^\\s*{{{ key }}}\\s*=" "${SETTINGSFILES[@]}"
    then
        {{% if '/' in key %}}
        {{{ raise("Key (" + key + ") uses sed path separator (/) in " + rule_id) }}}
        {{% endif %}}
        sed -Ei "s/(^\s*){{{ key }}}(\s*=)/#\1{{{ key }}}\2/g" "${SETTINGSFILES[@]}"
    fi
fi


[ ! -z "${DCONFFILE}" ] && echo "" >> "${DCONFFILE}"
if ! grep -q "\\[{{{ path }}}\\]" "${DCONFFILE}"
then
    printf '%s\n' "[{{{ path }}}]" >> ${DCONFFILE}
fi

escaped_value="$(sed -e 's/\\/\\\\/g' <<< "{{{ value }}}")"
if grep -q "^\\s*{{{ key }}}\\s*=" "${DCONFFILE}"
then
        sed -i "s/\\s*{{{ key }}}\\s*=\\s*.*/{{{ key }}}=${escaped_value}/g" "${DCONFFILE}"
    else
        sed -i "\\|\\[{{{ path }}}\\]|a\\{{{ key }}}=${escaped_value}" "${DCONFFILE}"
fi

dconf update
{{%- endmacro -%}}


{{#
    Macro to configure DConf locks for RHEL and Fedora systems.

#}}
{{%- macro bash_dconf_lock(key, setting, db, lock_file) -%}}
# Check for setting in any of the DConf db directories
LOCKFILES=$(grep -r "^/{{{ key }}}/{{{ setting }}}$" "/etc/dconf/db/" \
            | grep -v 'distro\|ibus\|{{{ db }}}' | grep ":" | cut -d":" -f1)
LOCKSFOLDER="/etc/dconf/db/{{{ db }}}/locks"

mkdir -p "${LOCKSFOLDER}"

# Comment out the configurations in databases different from the target one
if [[ ! -z "${LOCKFILES}" ]]
then
    sed -i -E "s|^/{{{ key }}}/{{{ setting }}}$|#&|" "${LOCKFILES[@]}"
fi

if ! grep -qr "^/{{{ key }}}/{{{ setting }}}$" /etc/dconf/db/{{{ db }}}/
then
    echo "/{{{ key }}}/{{{ setting }}}" >> "/etc/dconf/db/{{{ db }}}/locks/{{{ lock_file }}}"
fi

dconf update
{{%- endmacro -%}}


{{#
    Macro to enable or disable a particular service.

    Examples::

    bash_service_command("enable", "bluetooth")
    bash_service_command("disable", "bluetooth.service")
    bash_service_command("disable", "rsh.socket", xinetd="rsh")

:param service_state: Desired state of the service
:param service: The service to change
:param xinetd: Set the xinetd for the service. Defaults to empty string.

#}}
{{%- macro bash_service_command(service_state, service, xinetd="") -%}}
{{#
# If systemctl is installed, use systemctl command; otherwise, use the
# service/chkconfig commands
#}}
{{%- if init_system == "systemd" -%}}
  {{%- if service_state == "disable" -%}}
/usr/bin/systemctl stop "{{{ service }}}"
/usr/bin/systemctl disable "{{{ service }}}"
  {{%- else -%}}
/usr/bin/systemctl enable "{{{ service }}}"
/usr/bin/systemctl start "{{{ service }}}"
  {{%- endif %}}
# The service may not be running because it has been started and failed,
# so let's reset the state so OVAL checks pass.
# Service should be 'inactive', not 'failed' after reboot though.
/usr/bin/systemctl reset-failed "{{{ service }}}"
{{%- endif -%}}

{{%- if xinetd != "" -%}}
grep -qi disable "/etc/xinetd.d/$xinetd" && \
    {{%- if service_state == "disable" -%}}
sed -i "s/disable.*/disable         = no/gI" "/etc/xinetd.d/$xinetd"
    {{%- else -%}}
sed -i "s/disable.*/disable         = yes/gI" "/etc/xinetd.d/$xinetd"
    {{%- endif -%}}
{{%- endif -%}}
{{%- endmacro -%}}


{{%- macro _put_into_firefox_cfg(config_item, key, value_varname, where, sed_separator) -%}}
# If the key exists, change it. Otherwise, add it to the config_file.
if LC_ALL=C grep -m 1 -q '^{{{ config_item }}}("{{{ key }}}", ' "{{{ where }}}"; then
    {{% if sed_separator in config_item %}}
    {{{ raise("config_item (" + config_item + ") uses sed path separator (" + sed_separator + ") in " + rule_id) }}}
    {{% elif sed_separator in key %}}
    {{{ raise("key (" + key + ") uses sed path separator (" + sed_separator + ") in " + rule_id) }}}
    {{% endif %}}
    sed -i 's{{{ sed_separator }}}{{{ config_item }}}("{{{ key }}}".*{{{ sed_separator }}}{{{ config_item }}}("{{{ key }}}", '"${{{ value_varname }}})"';{{{ sed_separator }}}g' "{{{ where }}}"
else
    echo '{{{ config_item }}}("{{{ key }}}", '"${{{ value_varname }}}"');' >> "{{{ where }}}"
fi
{{%- endmacro -%}}


{{%- macro _make_bash_variable_assignment(varname, value="", quoted_value="") -%}}
{{% if value -%}}
    {{{ varname }}}="{{{ value }}}"
{{%- elif quoted_value -%}}
    {{{ varname }}}="\"{{{ quoted_value }}}\""
{{%- else %}}
    {{{ raise("Specify either 'value' or 'quoted_value' as macro arguments.") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#

Example Calls:

    With a fixed integer value::

        bash_firefox_js_setting("local-settings.js", "general.config.obscure_value", "0")

    With a fixed string value::

        bash_firefox_js_setting("local-settings.js", "general.config.filename", quoted_value="mozilla.cfg")

    With a string variable::

        bash_firefox_js_setting("local-settings.js", "general.config.filename", quoted_value="$var_config_file_name")

:param config_file:          Configuration file that will be modified
:param key:                  Configuration option to change
:param value:                Value of the configuration option to change

#}}
{{%- macro bash_firefox_js_setting(config_file, key, value="", quoted_value="", sed_separator="/") %}}
{{{ _make_bash_variable_assignment(varname="value", value=value, quoted_value=quoted_value) }}}
firefox_js="{{{ config_file }}}"
firefox_dirs="/usr/lib/firefox /usr/lib64/firefox /usr/local/lib/firefox /usr/local/lib64/firefox"
firefox_pref="defaults/pref"
firefox_preferences="defaults/preferences"

# Check the possible Firefox install directories
for firefox_dir in ${firefox_dirs}; do
    # If the Firefox directory exists, then Firefox is installed
    if [ -d "${firefox_dir}" ]; then
        # Different versions of Firefox have different preferences directories, check for them and set the right one
        if [ -d "${firefox_dir}/${firefox_preferences}" ] ; then
            firefox_pref_dir="${firefox_dir}/${firefox_preferences}"
        elif [ -d "${firefox_dir}/${firefox_pref}" ] ; then
            firefox_pref_dir="${firefox_dir}/${firefox_pref}"
        else
            firefox_pref_dir="${firefox_dir}/${firefox_preferences}"
            mkdir -p "${firefox_pref_dir}"
            chmod 755 "${firefox_pref_dir}"
        fi

        # Make sure the Firefox .js file exists and has the appropriate permissions
        if ! [ -f "${firefox_pref_dir}/${firefox_js}" ] ; then
            touch "${firefox_pref_dir}/${firefox_js}"
            chmod 644 "${firefox_pref_dir}/${firefox_js}"
        fi

        {{{ _put_into_firefox_cfg(config_item="pref", key=key, value_varname="value", where="${firefox_pref_dir}/${firefox_js}", sed_separator=sed_separator) | indent(4 * 2) }}}
    fi
done
{{%- endmacro -%}}


{{#
Function to replace configuration setting(s) in the Firefox preferences configuration (.cfg) file or add the
preference if it does not exist.


Example Call(s):

    Without string or variable::

        bash_firefox_cfg_setting("mozilla.cfg" "extensions.update.enabled" value="false")

    With string::

        bash_firefox_cfg_setting("mozilla.cfg" "security.default_personal_cert" quoted_value="Ask Every Time")

    With a string variable::

        bash_firefox_cfg_setting("mozilla.cfg" "browser.startup.homepage" quoted_value="${var_default_home_page}")

:param config_file:           Configuration file that will be modified
:param  key:                  Configuration option to change
:param  value:                Value of the configuration option to change

#}}
{{%- macro bash_firefox_cfg_setting(config_file, key, value="", quoted_value="", sed_separator="/") %}}
firefox_cfg="{{{ config_file }}}"
{{{ _make_bash_variable_assignment(varname="value", value=value, quoted_value=quoted_value) }}}
firefox_dirs="/usr/lib/firefox /usr/lib64/firefox /usr/local/lib/firefox /usr/local/lib64/firefox"

# Check the possible Firefox install directories
for firefox_dir in ${firefox_dirs}; do
    # If the Firefox directory exists, then Firefox is installed
    if [ -d "${firefox_dir}" ]; then
        # Make sure the Firefox .cfg file exists and has the appropriate permissions
        if ! [ -f "${firefox_dir}/${firefox_cfg}" ] ; then
            echo "//  IMPORTANT: Start your code on the 2nd line" > "${firefox_dir}/${firefox_cfg}"
            chmod 644 "${firefox_dir}/${firefox_cfg}"
        elif ! head -1 "${firefox_dir}/${firefox_cfg}" | grep -q "^//"; then
            sed -i '1 i\// IMPORTANT: Start your code on the 2nd line' "${firefox_dir}/${firefox_cfg}"
        fi

        {{{ _put_into_firefox_cfg(config_item="lockPref", key=key, value_varname="value", where="${firefox_dir}/${firefox_cfg}", sed_separator=sed_separator) | indent(4 * 2) }}}
    fi
done
{{%- endmacro -%}}


{{#
    Macro to ensure that the ntp/chrony config file contains valid server entries.

:param config_file: Path to the ntp/chrony config file
:param servers_list: Comma-separated list of servers

#}}
{{%- macro bash_ensure_there_are_servers_in_ntp_compatible_config_file(config_file, servers_list) -%}}
if ! grep -q '#[[:space:]]*server' "{{{ config_file }}}" ; then
  for server in $(echo "{{{ servers_list }}}" | tr ',' '\n') ; do
    printf '\nserver %s' "$server" >> "{{{ config_file }}}"
  done
else
  sed -i 's/#[ \t]*server/server/g' "{{{ config_file }}}"
fi
{{%- endmacro -%}}


{{#
    Macro used to apply changes on authselect profiles. The command automatically creates a backup
    of the current settings before applying the changes. It is possible to inform a custom backup
    name through the "backup_name" parameter. If the "backup_name" parameter is not defined, the
    authselect default name is used. The default name is formed by the current date and time
    suffixed by 6 random alphanumeric characters. The authselect backups are stored in sub-folders
    inside the "/var/lib/authselect/backups" folder, identified by their respective backup names.
    Note: An existing backup can be overwritten if the same backup name is informed. If this is
    not desired, avoid defining a backup name.

:param backup_name:        Changes the default backup name used by authselect.

#}}
{{% macro bash_apply_authselect_changes(backup_name='') -%}}
{{%- if backup_name == '' %}}
authselect apply-changes -b
{{%- else %}}
authselect apply-changes -b --backup={{{ backup_name }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
    Enable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.
#}}
{{%- macro bash_enable_authselect_feature(feature) -%}}
{{{ bash_check_authselect_integrity() }}}
authselect enable-feature {{{ feature }}}
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Enable pam_faillock.so PAM module using authselect.
    If an authselect profile is not selected or the selected profile is not intact, the operation is aborted.
    If the operation is aborted, an informative message is shown in the remediation report.
#}}
{{%- macro bash_enable_pam_faillock_with_authselect() -%}}
{{{ bash_enable_authselect_feature('with-faillock') }}}
{{%- endmacro -%}}


{{#
    Enable pam_faillock.so PAM module by directly editing PAM files.
    This option is only recommended when authselect tool is not available for the system.
#}}
{{%- macro bash_enable_pam_faillock_directly_in_pam_files() -%}}
{{% if 'ubuntu' in product %}}
pam_file="/etc/pam.d/common-auth"
if ! grep -qE '^\s*auth\s+required\s+pam_faillock\.so\s+preauth.*$' "$pam_file" ; then
    sed -i --follow-symlinks '/^auth.*pam_unix\.so.*/i auth        required      pam_faillock.so preauth' "$pam_file"
fi
if ! grep -qE '^\s*auth\s+\[default=die\]\s+pam_faillock\.so\s+authfail.*$' "$pam_file" ; then
    sed -i --follow-symlinks '/^auth.*pam_unix\.so.*/a auth        [default=die]      pam_faillock.so authfail' "$pam_file"
fi
if ! grep -qE '^\s*auth\s+sufficient\s+pam_faillock\.so\s+authsucc.*$' "$pam_file" ; then
    sed -i --follow-symlinks '/^auth.*pam_faillock\.so.*authfail.*/a auth        sufficient      pam_faillock.so authsucc' "$pam_file"
fi

pam_file="/etc/pam.d/common-account"
if ! grep -qE '^\s*account\s+required\s+pam_faillock\.so.*$' "$pam_file" ; then
    echo 'account   required     pam_faillock.so' >> "$pam_file"
fi
{{% else %}}
AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
for pam_file in "${AUTH_FILES[@]}"
do
    if ! grep -qE '^\s*auth\s+required\s+pam_faillock\.so\s+(preauth silent|authfail).*$' "$pam_file" ; then
        sed -i --follow-symlinks '/^auth.*sufficient.*pam_unix\.so.*/i auth        required      pam_faillock.so preauth silent' "$pam_file"
        sed -i --follow-symlinks '/^auth.*required.*pam_deny\.so.*/i auth        required      pam_faillock.so authfail' "$pam_file"
        sed -i --follow-symlinks '/^account.*required.*pam_unix\.so.*/i account     required      pam_faillock.so' "$pam_file"
    fi
    sed -Ei 's/(auth.*)(\[default=die\])(.*pam_faillock\.so)/\1required     \3/g' "$pam_file"
done
{{% endif %}}
{{%- endmacro -%}}


{{%- macro bash_pam_faillock_enable() -%}}
if [ -f /usr/bin/authselect ]; then
    {{{ bash_enable_pam_faillock_with_authselect() }}}
else
    {{{ bash_enable_pam_faillock_directly_in_pam_files() }}}
fi
{{%- endmacro -%}}

{{#
    Validate an authselect custom profile integrity and ensures the correct file path is defined
    in the "PAM_FILE_PATH" variable. The macros which change PAM files are the same regardless of
    using authselect or not. The only change is the file path. However, this file path can change
    depending on the custom profile name used in the system. So, based on the informed PAM file,
    the macro will properly locate the correct profile and file to be edited in the authselect
    context. This sequence of commands is used in multiple PAM related macros.

    :param pam_file:    PAM config file.
#}}
{{%- macro bash_ensure_pam_variables_and_authselect_profile(pam_file) -%}}
{{{ bash_check_authselect_integrity() }}}
{{# the following macro ensures the CURRENT_PROFILE variable is properly set #}}
{{{ bash_ensure_authselect_custom_profile() }}}
PAM_FILE_NAME=$(basename "{{{ pam_file }}}")
PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}

{{#
    Enable pam_pwhistory.so PAM module according to the system capabilities.
    If authselect is present and the "with-pwhistory" feature is available, the feature will be enabled.
    If authselect is present but the "with-pwhistory" feature is not yet available, a custom profile will be used.
    If authselect is not present, PAM files will be directly edited.

    :param pam_file:    PAM config file.
    :param control:     PAM control flags.
    :param after_match: Regex used as reference to append a line, if necessary. Optional parameter.
                        Note: For this macro, there is a special value used to include a line at
                        the beginning of the file: "BOF"

#}}
{{%- macro bash_pam_pwhistory_enable(pam_file, control, after_match='') -%}}
if [ -f /usr/bin/authselect ]; then
    if authselect list-features minimal | grep -q with-pwhistory; then
        {{{ bash_enable_authselect_feature('with-pwhistory') | indent(8) }}}
    else
        {{# the following macro ensures the PAM_FILE_PATH variable is properly set #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
        {{{ bash_ensure_pam_module_line("$PAM_FILE_PATH", 'password', control, 'pam_pwhistory.so', after_match) | indent(8) }}}
    fi
else
    {{{ bash_ensure_pam_module_line(pam_file, 'password', control, 'pam_pwhistory.so', after_match) | indent(4) }}}
fi
{{%- endmacro -%}}

{{#
    Set pam_pwhistory.so PAM module options and values. In case the file
    /etc/security/pwhistory.conf is present in the system, the option is ensured there and removed
    from pam files to avoid conflicts or confusion.

:param pam_file:    PAM config file.
:param option:      pwhistory option e.g.: remember, retry, debug
:param value:       value of option

#}}
{{%- macro bash_pam_pwhistory_parameter_value(pam_file, option, value='') -%}}
PWHISTORY_CONF="/etc/security/pwhistory.conf"
if [ -f $PWHISTORY_CONF ]; then
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $PWHISTORY_CONF; then
        echo $line >> $PWHISTORY_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $PWHISTORY_CONF
    fi
    {{%- endif %}}
    {{{ bash_remove_pam_module_option_configuration(pam_file, 'password', '', 'pam_pwhistory.so', option ) | indent(4) }}}
else
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{{ bash_ensure_pam_module_option("$PAM_FILE_PATH", 'password', 'requisite', 'pam_pwhistory.so', option, value, '') | indent(4) }}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
fi
{{%- endmacro -%}}

{{#
    Sets PAM faillock module options and values. In case the file
    /etc/security/faillock.conf is present in the system, the option is removed from pam files
    since it is not needed there in that case.
    It also adds pam_faillock.so as required module for account.

:param option: faillock option eg. deny, unlock_time, fail_interval
:param value: value of option
:param authfail: check the pam_faillock.so conf line with authfail

#}}
{{%- macro bash_pam_faillock_parameter_value(option, value='', authfail=True) -%}}
{{% if 'ubuntu' in product %}}
AUTH_FILES=("/etc/pam.d/common-auth" "/etc/pam.d/password-auth")
{{% else %}}
AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
{{% endif %}}
FAILLOCK_CONF="/etc/security/faillock.conf"
if [ -f $FAILLOCK_CONF ]; then
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $FAILLOCK_CONF; then
        echo $line >> $FAILLOCK_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $FAILLOCK_CONF
    fi
    {{%- endif %}}
    for pam_file in "${AUTH_FILES[@]}"
    do
        {{{ bash_remove_pam_module_option_configuration("$pam_file",'auth','','pam_faillock.so', option ) | indent(8) }}}
    done
else
    for pam_file in "${AUTH_FILES[@]}"
    do
        if ! grep -qE '^\s*auth.*pam_faillock\.so (preauth|authfail).*{{{ option }}}' "$pam_file"; then
            {{%- if value == '' %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*silent.*/ s/$/ {{{ option }}}/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ {{{ option }}}/' "$pam_file"
            {{%- endif %}}
            {{%- else %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*silent.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "$pam_file"
            {{%- endif %}}
            {{%- endif %}}
        {{%- if value == '' %}}
        fi
        {{%- else %}}
        else
            sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*silent.*\)\('"{{{ option }}}"'=\)[0-9]\+\(.*\)/\1\2'"{{{ value }}}"'\3/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"{{{ option }}}"'=\)[0-9]\+\(.*\)/\1\2'"{{{ value }}}"'\3/' "$pam_file"
            {{%- endif %}}
        fi
        {{%- endif %}}
    done
fi
{{%- endmacro -%}}

{{#
    Print a message to stderr and exit the shell

:param message: The message to print.
:param rc: The error code (optional, default is 1)
:param action: What to do (optional, default is 'exit', can be also 'return' or anything else)
#}}
{{% macro die(message, rc=1, action="exit") -%}}
printf '%s\n' "{{{ message | replace('"', '\\"') }}}" >&2
{{{ action }}} {{{ rc }}}
{{%- endmacro %}}

{{#
    Add an entry to a text configuration file

:param path: path of the configuration file
:param parameter: the parameter to be set in the configuration file
:param value: the value of the parameter to be set in the configuration file
:param create: whether create the file specified by path if the file does not exits
:param insert_after: inserts the entry right after first line that matches regular expression specified by this argument, set to EOF to insert at the end of the file
:param insert_before: inserts the entry right before first line that matches regular expression specified by this argument, set to BOF to insert at the beginning of the file
:param insensitive: ignore case
:param separator: separates parameter from the value (literal)
:param separator_regex: regular expression that describes the separator and surrounding whitespace
:param prefix_regex: regular expression describing allowed leading characters at each line

#}}

{{%- macro set_config_file(path, parameter, value, create, insert_after, insert_before, insensitive=true, separator=" ", separator_regex="\s\+", prefix_regex="^\s*", sed_path_separator="/") -%}}
    {{%- set new_line = parameter+separator+value -%}}
    {{#- An escaped dollar in the parameter is escaped because of its significance for the shell, so when making a regex out of the parameter, we remove the shell escape, as the regex escape will do its thing. -#}}
    {{%- set line_regex = prefix_regex + ((parameter | replace("\\$", "$") | escape_regex) | replace("/", "\/")) + separator_regex -%}}
if [ -e "{{{ path }}}" ] ; then
    {{{ lineinfile_absent(path, line_regex, insensitive, sed_path_separator=sed_path_separator) | indent(4) }}}
else
    {{%- if create %}}
    touch "{{{ path }}}"
    {{%- else %}}
    {{{ die("Path '" + path + "' wasn't found on this system. Refusing to continue.", action="return") | indent(4) }}}
    {{%- endif %}}
fi
{{{ lineinfile_present(path, new_line, insert_after, insert_before, insensitive, sed_path_separator=sed_path_separator) }}}
{{%- endmacro -%}}

{{%- macro lineinfile_absent(path, regex, insensitive=true, sed_path_separator="/") -%}}
    {{%- if insensitive -%}}
        {{%- set modifier="Id" -%}}
    {{%- else -%}}
        {{%- set modifier="d" -%}}
    {{%- endif -%}}
    {{% if sed_path_separator in regex %}}
    {{{ raise("regex (" + regex + ") uses sed path separator (" + sed_path_separator + ") in " + rule_id) }}}
    {{% endif %}}
LC_ALL=C sed -i "{{{ sed_path_separator }}}{{{ regex }}}{{{ sed_path_separator }}}{{{ modifier }}}" "{{{ path }}}"
{{%- endmacro -%}}

{{%- macro lineinfile_absent_in_directory(dirname, regex, insensitive=true, filename_glob="*") -%}}
    {{%- if insensitive -%}}
        {{%- set modifier="Id" -%}}
    {{%- else -%}}
        {{%- set modifier="d" -%}}
    {{%- endif -%}}
LC_ALL=C sed -i "/{{{ regex }}}/{{{ modifier }}}" "{{{ dirname }}}"/{{{ filename_glob }}}
{{%- endmacro -%}}

{{%- macro lineinfile_present(path, line, insert_after="", insert_before="", insensitive=true, sed_path_separator="/") -%}}
    {{%- if insensitive -%}}
        {{%- set grep_args="-q -m 1 -i" -%}}
    {{%- else -%}}
        {{%- set grep_args="-q -m 1" -%}}
    {{%- endif -%}}
# make sure file has newline at the end
sed -i -e '$a\' "{{{ path }}}"

cp "{{{ path }}}" "{{{ path }}}.bak"
    {{%- if not (insert_after or insert_before)  or insert_after == "EOF" %}}
# Insert at the end of the file
printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    {{%- elif insert_before == "BOF" %}}
# Insert at the beginning of the file
printf '%s\n' "{{{ line }}}" > "{{{ path }}}"
cat "{{{ path }}}.bak" >> "{{{ path }}}"
    {{%- elif insert_after %}}
# Insert after the line matching the regex '{{{ insert_after }}}'
line_number="$(LC_ALL=C grep -n "{{{ insert_after }}}" "{{{ path }}}.bak" | LC_ALL=C sed 's{{{sed_path_separator}}}:.*{{{sed_path_separator}}}{{{sed_path_separator}}}g')"
if [ -z "$line_number" ]; then
    # There was no match of '{{{ insert_after }}}', insert at
    # the end of the file.
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
else
    head -n "$(( line_number ))" "{{{ path }}}.bak" > "{{{ path }}}"
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    tail -n "+$(( line_number + 1 ))" "{{{ path }}}.bak" >> "{{{ path }}}"
fi
    {{%- elif insert_before %}}
# Insert before the line matching the regex '{{{ insert_before }}}'.
line_number="$(LC_ALL=C grep -n "{{{ insert_before }}}" "{{{ path }}}.bak" | LC_ALL=C sed 's{{{sed_path_separator}}}:.*{{{sed_path_separator}}}{{{sed_path_separator}}}g')"
if [ -z "$line_number" ]; then
    # There was no match of '{{{ insert_before }}}', insert at
    # the end of the file.
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
else
    head -n "$(( line_number - 1 ))" "{{{ path }}}.bak" > "{{{ path }}}"
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    tail -n "+$(( line_number ))" "{{{ path }}}.bak" >> "{{{ path }}}"
fi
    {{%- else %}}
{{{ die("This remediation has been generated incorrectly.") }}}
    {{%- endif %}}
# Clean up after ourselves.
rm "{{{ path }}}.bak"
{{%- endmacro -%}}

{{#
  Generates bash script code that puts 'contents' into a file at 'filepath'

:param filepath: Filepath of the file to check
:param contents:  Contents that should be in the file

#}}
{{%- macro bash_file_contents(filepath='', contents='') %}}
cat << 'EOF' > {{{ filepath }}}
{{{ contents }}}
EOF
{{%- endmacro %}}

{{# Strips anchors regex around the banner text #}}
{{% macro bash_deregexify_banner_anchors(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/^\^\(.*\)\$$/\1/g')
{{%- endmacro %}}

{{# Strips multibanner regex and keeps only the first banner #}}
{{% macro bash_deregexify_multiple_banners(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/^(\(.*\.\)|.*)$/\1/g')
{{%- endmacro %}}

{{# Strips whitespace or newline regex #}}
{{% macro bash_deregexify_banner_space(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/\[\\s\\n\]+/ /g')
{{%- endmacro %}}

{{# Strips newline or newline escape sequence regex #}}
{{% macro bash_deregexify_banner_newline(banner_var_name, newline) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/(?:\[\\n\]+|(?:\\\\n)+)/{{{ newline }}}/g')
{{%- endmacro %}}

{{# Strips newline token for a newline escape sequence regex #}}
{{% macro bash_deregexify_banner_newline_token(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/(n)\*/\\n/g')
{{%- endmacro %}}

{{# Strips backslash regex #}}
{{% macro bash_deregexify_banner_backslash(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/\\//g')
{{%- endmacro %}}

{{% macro bash_ini_file_set(filename, section, key, value) -%}}
{{% set config_dir = "/".join(filename.split("/")[:-1]) %}}
# Try find '[{{{ section }}}]' and '{{{ key }}}' in '{{{ filename }}}', if it exists, set
# to '{{{ value }}}', if it isn't here, add it, if '[{{{ section }}}]' doesn't exist, add it there
if grep -qzosP '[[:space:]]*\[{{{ section }}}]([^\n\[]*\n+)+?[[:space:]]*{{{ key }}}' '{{{ filename }}}'; then
    {{% if '/' in key %}}
    {{{ raise("key (" + key + ") uses sed path separator (/) in " + rule_id) }}}
    {{% elif '/' in value %}}
    {{{ raise("value (" + value + ") uses sed path separator (/) in " + rule_id) }}}
    {{% endif %}}
    sed -i "s/{{{ key }}}[^(\n)]*/{{{ key }}}={{{ value }}}/" '{{{ filename }}}'
elif grep -qs '[[:space:]]*\[{{{ section }}}]' '{{{ filename }}}'; then
    sed -i "/[[:space:]]*\[{{{ section }}}]/a {{{ key }}}={{{ value }}}" '{{{ filename }}}'
else
    if test -d "{{{ config_dir }}}"; then
        printf '%s\n' '[{{{ section }}}]' "{{{ key }}}={{{ value }}}" >> '{{{ filename }}}'
    else
        echo "Config file directory '{{{ config_dir }}}' doesnt exist, not remediating, assuming non-applicability." >&2
    fi
fi
{{%- endmacro %}}

{{%- macro bash_sudo_remove_config(parameter, pattern) -%}}
for f in /etc/sudoers /etc/sudoers.d/* ; do
  if [ ! -e "$f" ] ; then
    continue
  fi
  matching_list=$(grep -P '^(?!#).*[\s]+{{{ pattern }}}.*$' $f | uniq )
  if ! test -z "$matching_list"; then
    while IFS= read -r entry; do
      # comment out "{{{ parameter }}}" matches to preserve user data
      sed -i "s/^${entry}$/# &/g" $f
    done <<< "$matching_list"

    /usr/sbin/visudo -cf $f &> /dev/null || echo "Fail to validate $f with visudo"
  fi
done
{{%- endmacro -%}}

{{% macro bash_sssd_ldap_config(parameter, value) -%}}
SSSD_CONF="/etc/sssd/sssd.conf"
LDAP_REGEX='[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*{{{ parameter }}}'
AD_REGEX='[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*id_provider[[:space:]]*=[[:space:]]*((?i)ad)[[:space:]]*$'
DOMAIN_REGEX="[[:space:]]*\[domain\/[^]]*]"

# Check if id_provider is not set to ad (Active Directory) which makes start_tls not applicable, note the -v option to invert the grep.
# Try to find [domain/..] and {{{ parameter }}} in sssd.conf, if it exists, set to '{{{ value }}}'
# if {{{ parameter }}} isn't here, add it
# if [domain/..] doesn't exist, add it here for default domain
if grep -qvzosP $AD_REGEX $SSSD_CONF; then
        if grep -qzosP $LDAP_REGEX $SSSD_CONF; then
                {{% if '#' in parameter %}}
                {{{ raise("parameter (" + parameter + ") uses sed path separator (#) in " + rule_id) }}}
                {{% endif %}}
                sed -i "s#{{{ parameter }}}[^(\n)]*#{{{ parameter }}} = {{{ value }}}#" $SSSD_CONF
        elif grep -qs $DOMAIN_REGEX $SSSD_CONF; then
                sed -i "/$DOMAIN_REGEX/a {{{ parameter }}} = {{{ value }}}" $SSSD_CONF
        else
                if test -f "$SSSD_CONF"; then
                        echo -e "[domain/default]\n{{{ parameter }}} = {{{ value }}}" >> $SSSD_CONF
                else
                        echo "Config file '$SSSD_CONF' doesnt exist, not remediating, assuming non-applicability." >&2
                fi
        fi
fi
{{%- endmacro %}}

{{#
  # Check whether or not a package is installed.
  #}}
{{%- macro bash_package_installed(pkgname) -%}}
{{%- if pkg_manager == "apt_get" -%}}
dpkg-query --show --showformat='${db:Status-Status}\n' "{{{ pkgname }}}" 2>/dev/null | grep -q installed
{{%- else -%}}
rpm --quiet -q "{{{ pkgname }}}"
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Set rule CCE value

    This macro gets the var cce_identifiers from the environment created by the build scripts.
    The cce_identifiers is a dictionary that contains either the 'cce':'CCENUM' record for the
    product this remediation is being built for, or it is empty.
#}}
{{%- macro set_cce_value() -%}}
{{% if cce_identifiers and 'cce' in cce_identifiers -%}}
cce="{{{ cce_identifiers['cce'] }}}"
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Macro to replace configuration setting in config file or add the configuration setting if
    it does not exist.

    Example Calls:

      With default format of 'key = value'::

        {{{ bash_replace_or_append('/etc/sysctl.conf', '^kernel.randomize_va_space', '2') }}}

      With custom key/value format::

        {{{ bash_replace_or_append('/etc/sysconfig/selinux', '^SELINUX=', 'disabled', '%s=%s') }}}

      With a variable::

        {{{ bash_replace_or_append('/etc/sysconfig/selinux', '^SELINUX=', "$var_selinux_state", '%s=%s') }}}


:param config_file: Configuration file that will be modified
:param key: Configuration option to change
:param value: Value of the configuration option to change
:param format: Optional argument, The printf-like format string that will be given stripped key and value as arguments, so e.g. ``%s=%s` will result in key=value substitution (i.e. without spaces around =)

#}}
{{%- macro bash_replace_or_append(config_file, key, value, format='%s = %s') -%}}

# Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
# Otherwise, regular sed command will do.
sed_command=('sed' '-i')
if test -L "{{{ config_file }}}"; then
    sed_command+=('--follow-symlinks')
fi

# Strip any search characters in the key arg so that the key can be replaced without
# adding any search characters to the config file.
stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "{{{ key }}}")

# shellcheck disable=SC2059
printf -v formatted_output "{{{ format }}}" "$stripped_key" "{{{ value }}}"

# If the key exists, change it. Otherwise, add it to the config_file.
# We search for the key string followed by a word boundary (matched by \>),
# so if we search for 'setting', 'setting2' won't match.
if LC_ALL=C grep -q -m 1 -i -e "{{{ key }}}\\>" "{{{ config_file }}}"; then
    escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
    "${sed_command[@]}" "s/{{{ key }}}\\>.*/$escaped_formatted_output/gi" "{{{ config_file }}}"
else
    # \n is precaution for case where file ends without trailing newline
    {{% if cce_identifiers and 'cce' in cce_identifiers -%}}
    {{{ set_cce_value() }}}
    printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "{{{ config_file }}}" >> "{{{ config_file }}}"
    {{%- endif %}}
    printf '%s\n' "$formatted_output" >> "{{{ config_file }}}"
fi
{{%- endmacro -%}}

{{#
    Macro to restrict permissions in home directories of interactive users.
#}}
{{%- macro bash_restrict_permissions_home_directories(recursive=false) -%}}
for home_dir in $(awk -F':' '{ if ($3 >= {{{ uid_min }}} && $3 != {{{ nobody_uid }}}) print $6 }' /etc/passwd); do
    # Only update the permissions when necessary. This will avoid changing the inode timestamp when
    # the permission is already defined as expected, therefore not impacting in possible integrity
    # check systems that also check inodes timestamps.
    {{%- if recursive %}}
    find "$home_dir" -perm /7027 -exec chmod u-s,g-w-s,o=- {} \;
    {{%- else %}}
    find "$home_dir" -maxdepth 0 -perm /7027 -exec chmod u-s,g-w-s,o=- {} \;
    {{%- endif %}}
done
{{%- endmacro -%}}

{{#
    To see how args corresponds to an :code:`/etc/fstab` entry, see
    `bash_ensure_mount_option_for_vfstype <#template-bash_ensure_mount_option_in_fstab>`_
    documentation

:param vfstype:     type of filesystem
:param mount_opt:   mount point option which we are checking
:param fs_spec:     identification of the filesystem to be mounted (LABEL, UUID, device name etc.)
:param type:        mount type of new mount point (used when adding new entry in fstab)

#}}
{{% macro bash_ensure_mount_option_for_vfstype(vfstype, mount_opt, filesystem, type) -%}}
vfstype_points=()
readarray -t vfstype_points < <(grep -E "[[:space:]]{{{ vfstype }}}[[:space:]]" /etc/fstab | awk '{print $2}')

for vfstype_point in "${vfstype_points[@]}"
do
    {{{ bash_ensure_mount_option_in_fstab("${vfstype_point//\\\\/\\\\\\\\}", mount_opt, fs_spec, type) | indent(4) }}}
done
{{%- endmacro %}}

{{#
Ensures that given mount point is in :code:`/etc/fstab`.

    If we look at an example invocation of this macro::

        {{{ bash_ensure_mount_option_in_fstab("/home", "auto_da_alloc", "LABEL=t-home2", "ext4") }}}}

    The resulting :code:`/etc/fstab` entry could look like this::

        LABEL=t-home2   /home      ext4    defaults,auto_da_alloc      0  2

    :param mount_point: mount point
    :param mount_opt:   mount point option whose presence in /etc/fstab we are ensuring
    :param fs_spec:     identification of the filesystem to be mounted (LABEL, UUID, device name etc.)
    :param type:        mount type of mount point (used when adding new entry in fstab)
#}}
{{% macro bash_ensure_mount_option_in_fstab(mount_point, mount_opt, fs_spec, type) -%}}
mount_point_match_regexp="$(printf "[[:space:]]%s[[:space:]]" {{{ mount_point }}})"

# If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
if [ "$(grep -c "$mount_point_match_regexp" /etc/fstab)" -eq 0 ]; then
    # runtime opts without some automatic kernel/userspace-added defaults
    previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                | sed -E "s/(rw|defaults|seclabel|{{{ mount_opt }}})(,|$)//g;s/,$//")
    [ "$previous_mount_opts" ] && previous_mount_opts+=","
    echo "{{{ fs_spec }}} {{{ mount_point }}} {{{ type }}} defaults,${previous_mount_opts}{{{ mount_opt }}} 0 0" >> /etc/fstab
# If the mount_opt option is not already in the mount point's /etc/fstab entry, add it
elif [ "$(grep "$mount_point_match_regexp" /etc/fstab | grep -c "{{{ mount_opt }}}")" -eq 0 ]; then
    previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/fstab | awk '{print $4}')
    sed -i "s|\(${mount_point_match_regexp}.*${previous_mount_opts}\)|\1,{{{ mount_opt }}}|" /etc/fstab
fi
{{%- endmacro %}}

{{#
  # Check whether mount_point is present in /etc/fstab; print err to stderr and return 1 if not
  #}}
{{% macro bash_assert_mount_point_in_fstab(mount_point) -%}}
mount_point_match_regexp="$(printf "[[:space:]]%s[[:space:]]" "{{{ mount_point }}}")"
{{#
# This macro gets expanded to code that will return 1 if MOUNTPOINT is not in /etc/fstab;
# This is consistent with the behavior prior to converting this function to a jinja macro
#}}
grep "$mount_point_match_regexp" -q /etc/fstab \
    || { echo "The mount point '{{{ mount_point }}}' is not even in /etc/fstab, so we can't set up mount options" >&2;
            echo "Not remediating, because there is no record of {{{ mount_point }}} in /etc/fstab" >&2; return 1; }
{{%- endmacro %}}

{{#
  # Ensure that partition is mounted at mount_point
  # If partition already mounted at mount_point, then remount to apply option changes
  #}}
{{% macro bash_ensure_partition_is_mounted(mount_point) -%}}
if mkdir -p "{{{ mount_point }}}"; then
    if mountpoint -q "{{{ mount_point }}}"; then
        mount -o remount --target "{{{ mount_point }}}"
    else
        mount --target "{{{ mount_point }}}"
    fi
fi
{{%- endmacro %}}

{{#
Based on example audit syscall rule definitions as outlined in
:code:`/usr/share/doc/audit-2.3.7/stig.rules` file provided with the audit
package. It will combine multiple system calls belonging to the same
syscall group into one audit rule (rather than to create audit rule per
different system call) to avoid audit infrastructure performance penalty
in the case of 'one-audit-rule-definition-per-one-system-call'. See:

  https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html

for further details.

Notes:

* The 2-nd up to 4-th arguments are used to determine how many existing audit rules will be inspected for resemblance with the new audit rule the macro is going to add.
* The macro's similarity check uses the 5-th argument to optimize audit rules definitions (merge syscalls of the same group into one rule) to avoid the "single-syscall-per-audit-rule" performance penalty.
* The key argument (7-th argument) is not used when the syscall is grouped to an
existing audit rule. The audit rule will retain the key it already had.

:param audit_tool:  tool used to load audit rules, either 'auditctl', or 'augenrules
:param action_arch_filters: The action and arch filters of the rule. For example, "-a always,exit -F arch=b64"
:param other_filters: Other filters that may characterize the rule. For example, "-F a2&03 -F path=/etc/passwd"
:param auid_filters: The auid filters of the rule. For example, "-F auid>=1000 -F auid!=unset"
:param syscall: The syscall to ensure presense among audit rules. For example, "chown"
:param syscall_groupings: Other syscalls that can be grouped with 'syscall' as a space separated list. For example, "fchown lchown fchownat"
:param  key: The key to use when appending a new rule


#}}
{{% macro bash_fix_audit_syscall_rule(tool, action_arch_filters, other_filters, auid_filters, syscall, syscall_groupings, key) -%}}


unset syscall_a
unset syscall_grouping
unset syscall_string
unset syscall
unset file_to_edit
unset rule_to_edit
unset rule_syscalls_to_edit
unset other_string
unset auid_string
unset full_rule

# Load macro arguments into arrays
read -a syscall_a <<< {{{ syscall }}}
read -a syscall_grouping <<< {{{ syscall_groupings }}}

# Create a list of audit *.rules files that should be inspected for presence and correctness
# of a particular audit rule. The scheme is as follows:
#
# -----------------------------------------------------------------------------------------
#  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
# -----------------------------------------------------------------------------------------
#        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
# -----------------------------------------------------------------------------------------
#        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
#        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
# -----------------------------------------------------------------------------------------
#
files_to_inspect=()


{{% if tool == "auditctl" %}}
# If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
# file to the list of files to be inspected
default_file="/etc/audit/audit.rules"
files_to_inspect+=('/etc/audit/audit.rules' )
{{%- else -%}}
# If audit tool is 'augenrules', then check if the audit rule is defined
# If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
# If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
default_file="/etc/audit/rules.d/{{{ key }}}.rules"
# As other_filters may include paths, lets use a different delimiter for it
# The "F" script expression tells sed to print the filenames where the expressions matched
readarray -t files_to_inspect < <(sed -s -n -e "/^{{{ action_arch_filters }}}/!d" -e "\#{{{ other_filters }}}#!d" -e "/{{{ auid_filters }}}/!d" -e "F" /etc/audit/rules.d/*.rules)
# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
if [ ${#files_to_inspect[@]} -eq "0" ]
then
    file_to_inspect="/etc/audit/rules.d/{{{ key }}}.rules"
    files_to_inspect=("$file_to_inspect")
    if [ ! -e "$file_to_inspect" ]
    then
        touch "$file_to_inspect"
        chmod 0640 "$file_to_inspect"
    fi
fi
{{%- endif %}}

# After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
skip=1

for audit_file in "${files_to_inspect[@]}"
do
    # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
    # i.e, collect rules that match:
    # * the action, list and arch, (2-nd argument)
    # * the other filters, (3-rd argument)
    # * the auid filters, (4-rd argument)
    readarray -t similar_rules < <(sed -e "/^{{{ action_arch_filters }}}/!d"  -e "\#{{{ other_filters }}}#!d" -e "/{{{ auid_filters }}}/!d" "$audit_file")

    candidate_rules=()
    # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
    for s_rule in "${similar_rules[@]}"
    do
        # Strip all the options and fields we know of,
        # than check if there was any field left over
        extra_fields=$(sed -E -e "s/^{{{ action_arch_filters }}}//"  -e "s#{{{ other_filters }}}##" -e "s/{{{ auid_filters }}}//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
        grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
    done

    if [[ ${#syscall_a[@]} -ge 1 ]]
    then
        # Check if the syscall we want is present in any of the similar existing rules
        for rule in "${candidate_rules[@]}"
        do
            rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
            all_syscalls_found=0
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                   # A syscall was not found in the candidate rule
                   all_syscalls_found=1
                   }
            done
            if [[ $all_syscalls_found -eq 0 ]]
            then
                # We found a rule with all the syscall(s) we want; skip rest of macro
                skip=0
                break
            fi

            # Check if this rule can be grouped with our target syscall and keep track of it
            for syscall_g in "${syscall_grouping[@]}"
            do
                if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                then
                    file_to_edit=${audit_file}
                    rule_to_edit=${rule}
                    rule_syscalls_to_edit=${rule_syscalls}
                fi
            done
        done
    else
        # If there is any candidate rule, it is compliant; skip rest of macro
        if [ "${#candidate_rules[@]}" -gt 0 ]
        then
            skip=0
        fi
    fi

    if [ "$skip" -eq 0 ]; then
        break
    fi
done

if [ "$skip" -ne 0 ]; then
    # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
    # At this point we know if we need to either append the $full_rule or group
    # the syscall together with an exsiting rule

    # Append the full_rule if it cannot be grouped to any other rule
    if [ -z ${rule_to_edit+x} ]
    then
        # Build full_rule while avoid adding double spaces when other_filters is empty
        if [ "${#syscall_a[@]}" -gt 0 ]
        then
            syscall_string=""
            for syscall in "${syscall_a[@]}"
            do
                syscall_string+=" -S $syscall"
            done
        fi
        other_string=$([[ {{{ other_filters }}} ]] && echo " {{{ other_filters }}}") || /bin/true
        auid_string=$([[ {{{ auid_filters }}} ]] && echo " {{{ auid_filters }}}") || /bin/true
        full_rule="{{{ action_arch_filters }}}${syscall_string}${other_string}${auid_string} -F key={{{ key }}}" || /bin/true
        echo "$full_rule" >> "$default_file"
        chmod o-rwx ${default_file}
    else
        # Check if the syscalls are declared as a comma separated list or
        # as multiple -S parameters
        if grep -q -- "," <<< "${rule_syscalls_to_edit}"
        then
            delimiter=","
        else
            delimiter=" -S "
        fi
        new_grouped_syscalls="${rule_syscalls_to_edit}"
        for syscall in "${syscall_a[@]}"
        do
            grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
               # A syscall was not found in the candidate rule
               new_grouped_syscalls+="${delimiter}${syscall}"
               }
        done

        # Group the syscall in the rule
        sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
    fi
fi
{{%- endmacro %}}

{{#
    Ensures that /etc/default/grub file contains the arg_name_value.

:param arg_name: name of the grub parameter, e.g.: "audit"
:param arg_name_value: parameter together with the value to ensure, e.g.: "audit=1"

#}}
{{%- macro update_etc_default_grub_manually(arg_name, arg_name_value) -%}}
# Correct the form of default kernel command line in GRUB
if grep -q '^GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"'  '/etc/default/grub' ; then
       # modify the GRUB command-line if an {{{ arg_name }}}= arg already exists
       sed -i "s/\(^GRUB_CMDLINE_LINUX=\".*\){{{ arg_name }}}=[^[:space:]]\+\(.*\"\)/\1{{{ arg_name_value }}}\2/"  '/etc/default/grub'
else
       # no {{{ arg_name }}}=arg is present, append it
       sed -i "s/\(^GRUB_CMDLINE_LINUX=\".*\)\"/\1 {{{ arg_name_value }}}\"/"  '/etc/default/grub'
fi
{{%- endmacro %}}

{{#
Macro for Bash remediation for adding a kernel command line argument to the GRUB 2 bootloader.
Part of the grub2_bootloader_argument template.

:param arg_name: Kernel command line argument
:type arg_name str:
:param arg_name_value: Kernel command line argument concatenated with the value of this argument using an equal sign, eg. "noexec=off".
:type arg_name_value str:

#}}
{{% macro grub2_bootloader_argument_remediation(arg_name, arg_name_value) %}}
{{% if 'ubuntu' in product or product in ['rhel7', 'ol7', 'sle12', 'sle15'] %}}
{{{ update_etc_default_grub_manually(arg_name, arg_name_value) }}}
{{% endif -%}}
{{{ grub_command("add", arg_name_value) }}}
{{% endmacro %}}

{{#
    Ensures that /etc/default/grub file does not contain the arg_name_value.
:param arg_name: name of the grub parameter, e.g.: "audit"

#}}
{{%- macro update_etc_default_grub_manually_absent(arg_name) -%}}
# Correct the form of default kernel command line in GRUB
if grep -q '^GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"'  '/etc/default/grub' ; then
       sed -i 's/\(^GRUB_CMDLINE_LINUX=".*\){{{ arg_name }}}=?[^[:space:]]*\(.*"\)/\1 \2/' '/etc/default/grub'
fi
{{%- endmacro %}}

{{#
Macro for Bash remediation for removing a kernel command line argument from the GRUB 2 bootloader.
Part of the grub2_bootloader_argument_absent template.

:param arg_name: Name of the kernel command line argument that will be removed from GRUB 2 configuration.
:type arg_name str:

#}}
{{% macro grub2_bootloader_argument_absent_remediation(arg_name) %}}
{{% if 'ubuntu' in product or product in ['rhel7', 'ol7', 'sle12', 'sle15'] %}}
{{{ update_etc_default_grub_manually_absent(arg_name) }}}
{{% endif -%}}
{{{ grub_command("remove", arg_name) }}}
{{% endmacro %}}

{{#
  This macro creates a bash conditional which is used to determine if a remediation is applicable.
  The macro takes package as an argument and chooses appropriate package manager.
  If the package is installed, the Bash remediation will be applied.
  The macro respects `platform_package_overrides` variable.
#}}
{{%- macro bash_pkg_conditional(package, escape=False) -%}}
{{%- if package in platform_package_overrides -%}}
  {{%- set package = platform_package_overrides[package] -%}}
{{%- endif -%}}
  {{% if pkg_system is defined %}}
    {{%- if pkg_system == "rpm" -%}}
        {{{ bash_pkg_conditional_rpm(package) }}}
    {{%- elif pkg_system == "dpkg" -%}}
        {{{ bash_pkg_conditional_dpkg(package, escape) }}}
    {{%- else -%}}
JINJA MACRO ERROR - Unknown package system '{{{ pkg_system }}}'.
    {{%- endif -%}}
{{% endif %}}
{{%- endmacro -%}}


{{#
  This macro creates a Bash conditional which uses rpm to check if a package passed as a parameter is installed.
#}}
{{%- macro bash_pkg_conditional_rpm(package) -%}}
rpm --quiet -q {{{ package }}}
{{%- endmacro %}}

{{#
  This macro creates a Bash conditional which uses dpkg to check if a package passed as a parameter is installed.
#}}
{{%- macro bash_pkg_conditional_dpkg (package, escape=False) -%}}
{{%- if escape -%}}
dpkg-query --show --showformat='${{db:Status-Status}}\n' '{{{ package }}}' 2>/dev/null | grep -q installed
{{%- else -%}}
dpkg-query --show --showformat='${db:Status-Status}\n' '{{{ package }}}' 2>/dev/null | grep -q installed
{{%- endif -%}}
{{%- endmacro -%}}

{{#
Macro to replace configuration setting(s) in the Chromium stig policy (.json) file or add the
preference if it does not exist.

Example macro invocation:

    {{{ bash_chromium_pol_setting("chrome_stig_policy.json", "/etc/chromium/policies/managed/", "ExtensionInstallBlacklist", "\[\"*\"\]") }}}

:param  chrome_pol_file:      Policy file to that will be modified
:param  chrome_pol_dir:       Directory where the policy file is located
:param  pol_setting:          The setting that will be modified
:param  pol_setting_val:      Value of the setting to replace the current value with
:param  pol_setting_val_edit: Value of the setting to be inserted if setting and value not present

#}}
{{%- macro bash_chromium_pol_setting(chrome_pol_file, chrome_pol_dir, pol_setting, pol_setting_val, pol_setting_val_edit=None) %}}
{{% if not pol_setting_val_edit %}}
{{% set pol_setting_val_edit = pol_setting_val %}}
{{% endif %}}

if ! grep -q {{{ pol_setting }}} {{{ chrome_pol_dir }}}{{{ chrome_pol_file }}}; then
   sed -i -e '/{/a \  "'{{{ pol_setting }}}'": '{{{ pol_setting_val_edit }}}',' {{{ chrome_pol_dir }}}{{{ chrome_pol_file }}}
else
   sed -i -e 's/\"'{{{ pol_setting }}}'.*/\"'{{{ pol_setting }}}'\": '{{{ pol_setting_val }}}',/g' {{{ chrome_pol_dir }}}{{{ chrome_pol_file }}}
fi
{{%- endmacro -%}}


{{#
    Macro that lets you define the body of a loop that iterates over the output of the find command
    Use with the call block syntax {{% call iterate_over_find_output("fname", "mydir -name *.conf") %}} ...
#}}
{{% macro iterate_over_find_output(varname, find_args="") -%}}
while IFS= read -r -d '' {{{ varname }}}; do
    {{{ caller() | indent(4) }}}
done <   <(find {{{ find_args }}} -print0)
{{%- endmacro %}}


{{#
    Macro that lets you define the body of a loop that iterates over the output of any command
    Use with the call block syntax {{% call iterate_over_find_output("fname", "awk ... myfile") %}} ...
#}}
{{% macro iterate_over_command_output(varname, command_and_its_args) -%}}
while IFS= read -r {{{ varname }}}; do
    {{{ caller() | indent(4) }}}
done <   <({{{ command_and_its_args }}})
{{%- endmacro %}}


{{#
  # Ensure key is set to correct value under a correct section in an .ini style config file

:param files:   list of space-separated files to add key = value to (may contain wildcards)
                if none contain section, create and append to FIRST file
:param section: section to add key = value under
:param key:     key
:param value:   value

Example macro invocation(s):

    bash_ensure_ini_config("/etc/sssd/sssd.conf", "pam", "offline_credentials_expiration", "1")
    bash_ensure_ini_config("/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf", "sssd", "user", "sssd")

#}}
{{% macro bash_ensure_ini_config(files, section, key, value) -%}}
found=false

# set value in all files if they contain section or key
for f in $(echo -n "{{{ files }}}"); do
    if [ ! -e "$f" ]; then
        continue
    fi

    # find key in section and change value
    if grep -qzosP "[[:space:]]*\[{{{ section }}}\]([^\n\[]*\n+)+?[[:space:]]*{{{ key }}}" "$f"; then
            sed -i "s/{{{ key }}}[^(\n)]*/{{{ key }}} = {{{ value }}}/" "$f"
            found=true

    # find section and add key = value to it
    elif grep -qs "[[:space:]]*\[{{{ section }}}\]" "$f"; then
            sed -i "/[[:space:]]*\[{{{ section }}}\]/a {{{ key }}} = {{{ value }}}" "$f"
            found=true
    fi
done

# if section not in any file, append section with key = value to FIRST file in files parameter
if ! $found ; then
    file=$(echo "{{{ files }}}" | cut -f1 -d ' ')
    mkdir -p "$(dirname "$file")"
    echo -e "[{{{ section }}}]\n{{{ key }}} = {{{ value }}}" >> "$file"
fi
{{%- endmacro %}}


{{#
    Make sure that a line with a specific PAM module is present with the correct control.
    If the line is not present, it will be included after the regex informed in the "after_match"
    parameter. If the "after_match" parameter is empty, the line will be included at the end of
    the file informed in the "pam_file" parameter.
    If the line was already present, but with a different control, the control will be updated.
    Note: If there are multiple lines matching the "group" + "module", no lines will be updated.
    Instead, a new line will be included after the regex informed in "after_match" or at the
    end of file if "after_match" parameter is empty or there is no match.
    This is a conservative safeguard for improper use of this macro in rare cases of modules
    configured by multiple lines, like pam_sss.so, pam_faillock.so and pam_lastlog.so. In some
    situations, these special modules may have similar lines sharing the same "group" and "module".
    For these specific cases, this macro is not recommened without careful tests to make sure the
    PAM module is working as expected. Otherwise, a custom remediation should be considered.

:param pam_file:        PAM config file.
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:param control:         PAM control flags.
:param module:          PAM module name.
:param after_match:     Regex used as reference to append a line, if necessary. Optional parameter.
                        Note: For this macro, there is a special value used to include a line at the beginning of the file: "BOF"

#}}
{{%- macro bash_ensure_pam_module_line(pam_file, group, control, module, after_match='') -%}}
if ! grep -qP '^\s*{{{ group }}}\s+'"{{{ control }}}"'\s+{{{ module }}}\s*.*' "{{{ pam_file }}}"; then
    # Line matching group + control + module was not found. Check group + module.
    if [ "$(grep -cP '^\s*{{{ group }}}\s+.*\s+{{{ module }}}\s*' "{{{ pam_file }}}")" -eq 1 ]; then
        # The control is updated only if one single line matches.
        sed -i -E --follow-symlinks 's/^(\s*{{{ group }}}\s+).*(\b{{{ module }}}.*)/\1'"{{{ control }}}"' \2/' "{{{ pam_file }}}"
    else
        {{%- if after_match == '' %}}
        echo '{{{ group }}}    '"{{{ control }}}"'    {{{ module }}}' >> "{{{ pam_file }}}"
        {{%- elif after_match == 'BOF'  %}}
        sed -i --follow-symlinks '1i {{{ group }}}     '"{{{ control }}}"'    {{{ module }}}' "{{{ pam_file }}}"
        {{%- else %}}
        LAST_MATCH_LINE=$(grep -nP "{{{ after_match }}}" "{{{ pam_file }}}" | tail -n 1 | cut -d: -f 1)
        if [ ! -z $LAST_MATCH_LINE ]; then
            sed -i --follow-symlinks $LAST_MATCH_LINE' a {{{ group }}}     '"{{{ control }}}"'    {{{ module }}}' "{{{ pam_file }}}"
        else
            echo '{{{ group }}}    '"{{{ control }}}"'    {{{ module }}}' >> "{{{ pam_file }}}"
        fi
        {{%- endif %}}
    fi
fi
{{%- endmacro -%}}


{{#
    Make sure that an existing PAM module line is properly configured with an option.

:param pam_file:        PAM config file.
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:param control:         PAM control flags.
:param module:          PAM module name.
:param option:          PAM module option.
:param value:           PAM module option argument, if is case. Optional parameter.
:param after_match:     Regex used as reference to include the PAM line below, if necessary. Optional parameter.

#}}
{{%- macro bash_ensure_pam_module_option(pam_file, group, control, module, option, value='', after_match='') -%}}
{{{ bash_ensure_pam_module_line(pam_file, group, control, module, after_match) }}}
# Check the option
if ! grep -qP '^\s*{{{ group }}}\s+'"{{{ control }}}"'\s+{{{ module }}}\s*.*\s{{{ option }}}\b' "{{{ pam_file }}}"; then
    {{%- if value == '' %}}
    sed -i -E --follow-symlinks '/\s*{{{ group }}}\s+'"{{{ control }}}"'\s+{{{ module }}}.*/ s/$/ {{{ option }}}/' "{{{ pam_file }}}"
    {{%- else %}}
    sed -i -E --follow-symlinks '/\s*{{{ group }}}\s+'"{{{ control }}}"'\s+{{{ module }}}.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "{{{ pam_file }}}"
    {{%- endif %}}
{{%- if value == '' %}}
fi
{{%- else %}}
else
    sed -i -E --follow-symlinks 's/(\s*{{{ group }}}\s+'"{{{ control }}}"'\s+{{{ module }}}\s+.*)('"{{{ option }}}"'=)[[:alnum:]]+\s*(.*)/\1\2'"{{{ value }}}"' \3/' "{{{ pam_file }}}"
fi
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Remove a PAM module option if present in a PAM module line.

:param pam_file:        PAM config file.
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:param control:         PAM control flags. Optional parameter, but recommended to be informed whenever possible.
:param module:          PAM module name.
:param option:          PAM module option.

#}}
{{%- macro bash_remove_pam_module_option(pam_file, group, control, module, option) -%}}
{{%- if control == '' %}}
if grep -qP '^\s*{{{ group }}}\s.*\b{{{ module }}}\s.*\b{{{ option }}}\b' "{{{ pam_file }}}"; then
    sed -i -E --follow-symlinks 's/(.*{{{ group }}}.*{{{ module }}}.*)\b{{{ option }}}\b=?[[:alnum:]]*(.*)/\1\2/g' "{{{ pam_file }}}"
{{%- else %}}
if grep -qP '^\s*{{{ group }}}\s+'"{{{ control }}}"'\s+{{{ module }}}\s.*\b{{{ option }}}\b' "{{{ pam_file }}}"; then
    sed -i -E --follow-symlinks 's/(.*{{{ group }}}.*'"{{{ control }}}"'.*{{{ module }}}.*)\s{{{ option }}}=?[[:alnum:]]*(.*)/\1\2/g' "{{{ pam_file }}}"
{{%- endif %}}
fi
{{%- endmacro -%}}


{{#
    Macro used to check if authselect files are intact. When used, it will exit the respective
    script if any authselect file was modified without proper use of authselect tool and
    respective profiles.
#}}
{{% macro bash_check_authselect_integrity() -%}}
if ! authselect check; then
echo "
authselect integrity check failed. Remediation aborted!
This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
It is not recommended to manually edit the PAM files when authselect tool is available.
In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
exit 1
fi
{{%- endmacro %}}


{{#
    Macro used to ensure a custom authselect profile is in use before changing any PAM file.
    This macro is useful in cases where an authselect profile doesn't provide a feature to enable
    the desired PAM module or option. In these cases, a custom authselect profile is necessary.
    If the system already uses a custom authselect profile, no action is necessary. Otherwise, a
    new custom profile will be created based on the current profile and preserving the already
    enabled features. Custom profiles are only recommeded if an authselect feature for the same
    purpose is not available. In any case, this macro will also set the "CURRENT_PROFILE" variable
    which is also used in the "bash_ensure_pam_variables_and_authselect_profile" macro.
#}}
{{% macro bash_ensure_authselect_custom_profile() -%}}
CURRENT_PROFILE=$(authselect current -r | awk '{ print $1 }')
# If not already in use, a custom profile is created preserving the enabled features.
if [[ ! $CURRENT_PROFILE == custom/* ]]; then
    ENABLED_FEATURES=$(authselect current | tail -n+3 | awk '{ print $2 }')
    authselect create-profile hardening -b $CURRENT_PROFILE
    CURRENT_PROFILE="custom/hardening"
    {{{ bash_apply_authselect_changes('before-hardening-custom-profile') | indent(4) }}}
    authselect select $CURRENT_PROFILE
    for feature in $ENABLED_FEATURES; do
        authselect enable-feature $feature;
    done
    {{{ bash_apply_authselect_changes('after-hardening-custom-profile') | indent(4) }}}
fi
{{%- endmacro %}}


{{#
    Make sure that an existing PAM module line is properly configured, in aligment to the current
    system configuration. This macro is compatible with custom authselect profiles if the system
    relies on authselect. Otherwise, the PAM files will be directly edited.

:param pam_file:        PAM config file.
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:param control:         PAM control flags.
:param module:          PAM module name.
:param option:          PAM module option. Optional parameter.
:param value:           PAM module option argument, if is case. Optional parameter.
:param after_match:     Regex used as reference to include the PAM line below, if necessary. Optional parameter.

#}}
{{%- macro bash_ensure_pam_module_configuration(pam_file, group, control, module, option='', value='', after_match='') -%}}
if [ -e "{{{ pam_file }}}" ] ; then
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{%- if option == '' %}}
    {{{ bash_ensure_pam_module_line("$PAM_FILE_PATH", group, control, module, after_match) }}}
    {{%- else %}}
    {{{ bash_ensure_pam_module_option("$PAM_FILE_PATH", group, control, module, option, value, after_match) | indent(8) }}}
    {{%- endif %}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
else
    echo "{{{ pam_file }}} was not found" >&2
fi
{{%- endmacro -%}}

{{#
    Remove a PAM module option from an existing PAM module line. This macro is compatible with
    custom authselect profiles if the system relies on authselect. Otherwise, the PAM files will
    be directly edited.

:param pam_file:        PAM config file.
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:param control:         PAM control flags. Optional parameter, but recommended to be informed whenever possible.
:param module:          PAM module name.
:param option:          PAM module option.

#}}
{{%- macro bash_remove_pam_module_option_configuration(pam_file, group, control, module, option) -%}}
if [ -e "{{{ pam_file }}}" ] ; then
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{{ bash_remove_pam_module_option("$PAM_FILE_PATH", group, control, module, option) }}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
else
    echo "{{{ pam_file }}} was not found" >&2
fi
{{%- endmacro -%}}


{{%- macro bash_partition_conditional(path) -%}}
'findmnt --kernel "{{{ path }}}" > /dev/null'
{{%- endmacro -%}}


{{#
    Macro to insert script to find a Python interpreter on the target system.
#}}
{{% macro find_python() -%}}

declare __REMEDIATE_PYTHON
if [ -x /usr/bin/python ]; then
    __REMEDIATE_PYTHON=/usr/bin/python
elif [ -x /usr/bin/python3 ]; then
    __REMEDIATE_PYTHON=/usr/bin/python3
elif [ -x /usr/bin/python2 ]; then
    __REMEDIATE_PYTHON=/usr/bin/python2
else
    echo "Python required and no python interpreter found."
    exit 1
fi
{{%- endmacro %}}

{{#
    Macro to insert script to find Mozilla Firefox location on the target system.
#}}
{{% macro find_firefox() -%}}

declare __FIREFOX_DISTRIBUTION
if find /usr -iname firefox\* -type f -print | grep -qe "firefox.sh$\|firefox-bin$"; then
   __FIREFOX_DISTRIBUTION=$(dirname "$(find /usr -iname firefox\* -type f -print | grep -e "firefox.sh$\|firefox-bin$" | head -n1)")/distribution
fi
{{%- endmacro %}}


